package com.hxm.meizi.provider;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hxm.meizi.R;
import com.hxm.meizi.entity.ImageInfo;
import com.hxm.meizi.listener.OnItemClickListener;
import com.hxm.meizi.util.ImageLoader;

import me.drakeet.multitype.ItemViewProvider;

/**
 * Created by hxm on 2017/2/18.
 *
 */

public class ImageProvider extends ItemViewProvider<ImageInfo, ImageProvider.ImageHolder> {
    private OnItemClickListener listener;

    public ImageProvider(OnItemClickListener listener) {
        this.listener = listener;
    }

    @NonNull
    @Override
    protected ImageHolder onCreateViewHolder(@NonNull LayoutInflater inflater, @NonNull ViewGroup parent) {
        View view = inflater.inflate(R.layout.item_image_provider, parent, false);
        return new ImageHolder(view);
    }

    @Override
    protected void onBindViewHolder(@NonNull final ImageHolder holder, @NonNull final ImageInfo imageInfo) {
        Context context = holder.imageView.getContext();
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (listener != null) {
                    listener.click(imageInfo.getImageId());
                }
            }
        });
        ImageLoader.display(context, imageInfo.getImageUrl(), holder.imageView,
                holder.loading, holder.loadingError);
        holder.category.setText(imageInfo.getCategory());
        holder.times.setText(imageInfo.getViewTimes());
        holder.title.setText(imageInfo.getTitle());
        holder.date.setText(imageInfo.getDate());
    }

    static class ImageHolder extends RecyclerView.ViewHolder {
        private ImageView imageView;
        private TextView title, date, category, times;
        private LinearLayout loading, loadingError;

        public ImageHolder(View itemView) {
            super(itemView);
            times = (TextView) itemView.findViewById(R.id.tv_times);
            title = (TextView) itemView.findViewById(R.id.tv_title);
            date = (TextView) itemView.findViewById(R.id.tv_date);
            category = (TextView) itemView.findViewById(R.id.tv_category);
            imageView = (ImageView) itemView.findViewById(R.id.imageView);
            loading = (LinearLayout) itemView.findViewById(R.id.loading);
            loadingError = (LinearLayout) itemView.findViewById(R.id.loading_error);
        }
    }
}
